#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

int main() {
    int fd = open("io.txt", O_CREAT | O_WRONLY | O_APPEND, 0644);
    if (fd == -1) {
        perror("When open");
        exit(EXIT_FAILURE);
    }
    char buffer[1024];
    pid_t pid = fork();
    if (pid < 0) {
        perror("fork");
        exit(EXIT_FAILURE);
    }
    else if (pid == 0) {
        printf("子进程%d写入...\n", getpid());
        sprintf(buffer,"子进程%d写入\n", getpid());
    }
    else {
        sleep(1);
        printf("父进程%d写入...\n", getppid());
        sprintf(buffer,"父进程%d写入\n", getppid());
    }
    ssize_t bytes_write = write(fd, buffer, sizeof(buffer));
    printf("%d写入数据成功",getpid());
    close(fd);
    if (pid == 0) {
        printf("子进程写入结束，释放文件描述符\n");
    }
    else {
        printf("父进程写入结束，释放文件描述符\n"); 
    }
    return 0;
}